<?php

namespace app\common\job;

use think\facade\Config;

/**
 * 队列基础类
 */
class Queue
{
    private static ?self $_instance;

    public static function instance():static
    {
        if (!isset($people->name) || !self::$_instance){
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    // 私有化构造函数
    private function __construct()
    {
    }

    /**
     * 添加队列任务任务
     * @param $queue
     * @param $data
     * @param int $delay
     * @return mixed
     */
    public function send($queue, $data, int $delay = 0): mixed
    {
        $redisConfig = Config::get('micurr.redis');
        $redis = new \Redis();
        $redis->connect($redisConfig['host'], $redisConfig['port']);
        return $this->redis_queue_send($redis, $queue, $data, $delay);
    }

    private function redis_queue_send(\Redis $redis, $queue, $data, $delay = 0): bool|int
    {
        $queue_waiting = '{redis-queue}-waiting'; //1.0.5版本之前为redis-queue-waiting
        $queue_delay = '{redis-queue}-delayed';//1.0.5版本之前为redis-queue-delayed

        $now = time();
        $package_str = json_encode([
            'id'       => rand(),
            'time'     => $now,
            'delay'    => $delay,
            'attempts' => 0,
            'queue'    => $queue,
            'data'     => $data
        ]);
        if ($delay) {
            return $redis->zAdd($queue_delay, $now + $delay, $package_str);
        }
        return $redis->lPush($queue_waiting.$queue, $package_str);
    }

}
